package backed.service.impl;

import backed.entity.Order;
import backed.entity.SecondHandItem;
import backed.entity.User;
import backed.repository.OrderRepository;
import backed.repository.SecondHandItemRepository;
import backed.repository.UserRepository;
import backed.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Optional;
import java.util.Random;

@Service
public class OrderServicelmpl implements OrderService {
    @Autowired
    private OrderRepository orderRepository;
    
    @Autowired
    private UserRepository userRepository;
    
    @Autowired
    private SecondHandItemRepository secondHandItemRepository;

    @Override
    @Transactional
    public Order create(Long itemId, Long buyerId, String shippingAddress) {
        // 1. 获取商品信息
        SecondHandItem item = secondHandItemRepository.findById(itemId)
            .orElseThrow(() -> new IllegalArgumentException("商品不存在"));
        
        // 2. 检查商品状态
        if (!"on_sale".equals(item.getStatus())) {
            throw new IllegalArgumentException("商品已售出或已下架");
        }
        
        // 3. 创建订单对象
        Order order = new Order();
        
        // 4. 设置订单基本信息
        order.setItemId(itemId);
        order.setBuyerId(buyerId);
        order.setSellerId(item.getUserId()); // 从商品中获取卖家ID
        order.setAmount(item.getPrice()); // 使用商品价格作为订单金额
        order.setShippingAddress(shippingAddress);
        order.setStatus(Order.STATUS_PENDING); // 设置为待支付状态
        
        // 5. 生成唯一订单号
        order.setOrderNo(generateOrderNo());
        
        // 6. 设置时间戳
        Date now = new Date();
        order.setCreateTime(now);
        order.setUpdateTime(now);
        
        // 7. 保存订单
        Order savedOrder = orderRepository.save(order);
        
        // 8. 更新商品状态为已售出
        item.setStatus("sold");
        secondHandItemRepository.save(item);
        
        return savedOrder;
    }
    
    @Override
    @Transactional
    public Order payOrder(String orderNo) {
        // 1. 根据订单号查找订单
        Order order = orderRepository.findByOrderNo(orderNo)
            .orElseThrow(() -> new IllegalArgumentException("订单不存在"));
        
        // 2. 检查订单状态是否为待支付
        if (!Order.STATUS_PENDING.equals(order.getStatus())) {
            throw new IllegalArgumentException("订单状态不正确，无法支付");
        }
        
        // 3. 获取买家和卖家信息
        User buyer = userRepository.findById(order.getBuyerId())
            .orElseThrow(() -> new IllegalArgumentException("买家不存在"));
        User seller = userRepository.findById(order.getSellerId())
            .orElseThrow(() -> new IllegalArgumentException("卖家不存在"));
        
        // 4. 检查买家余额是否足够
        BigDecimal orderAmount = order.getAmount();
        BigDecimal buyerMoney = buyer.getMoney() != null ? buyer.getMoney() : BigDecimal.ZERO;
        
        if (buyerMoney.compareTo(orderAmount) < 0) {
            throw new IllegalArgumentException("余额不足，无法支付。当前余额：" + buyerMoney + "，订单金额：" + orderAmount);
        }
        
        // 5. 从买家余额中扣除订单金额
        BigDecimal newBuyerMoney = buyerMoney.subtract(orderAmount);
        buyer.setMoney(newBuyerMoney);
        userRepository.save(buyer);
        
        // 6. 将订单金额加到卖家余额中
        BigDecimal sellerMoney = seller.getMoney() != null ? seller.getMoney() : BigDecimal.ZERO;
        BigDecimal newSellerMoney = sellerMoney.add(orderAmount);
        seller.setMoney(newSellerMoney);
        userRepository.save(seller);
        
        // 7. 更新订单状态为已支付
        Date now = new Date();
        order.setStatus(Order.STATUS_PAID);
        order.setPayTime(now);
        order.setUpdateTime(now);
        
        // 8. 保存更新后的订单
        return orderRepository.save(order);
    }
    
    @Override
    @Transactional
    public Order shipOrder(String orderNo) {
        // 1. 根据订单号查找订单
        Order order = orderRepository.findByOrderNo(orderNo)
            .orElseThrow(() -> new IllegalArgumentException("订单不存在"));
        
        // 2. 检查订单状态是否为已支付
        if (!Order.STATUS_PAID.equals(order.getStatus())) {
            throw new IllegalArgumentException("订单状态不正确，只能对已支付订单进行发货操作");
        }
        
        // 3. 更新订单状态为已发货
        Date now = new Date();
        order.setStatus(Order.STATUS_SHIPPED);
        order.setUpdateTime(now);
        
        // 4. 保存更新后的订单
        return orderRepository.save(order);
    }
    
    @Override
    @Transactional
    public Order confirmOrder(String orderNo) {
        // 1. 根据订单号查找订单
        Order order = orderRepository.findByOrderNo(orderNo)
            .orElseThrow(() -> new IllegalArgumentException("订单不存在"));
        
        // 2. 检查订单状态是否为已发货
        if (!Order.STATUS_SHIPPED.equals(order.getStatus())) {
            throw new IllegalArgumentException("只有已发货的订单才能确认收货");
        }
        
        // 3. 更新订单状态为已完成
        Date now = new Date();
        order.setStatus(Order.STATUS_COMPLETED);
        order.setCompleteTime(now);
        order.setUpdateTime(now);
        
        // 4. 保存更新后的订单
        return orderRepository.save(order);
    }
    
    @Override
    @Transactional
    public Order cancelOrder(String orderNo) {
        // 1. 根据订单号查找订单
        Order order = orderRepository.findByOrderNo(orderNo)
            .orElseThrow(() -> new IllegalArgumentException("订单不存在"));
        
        // 2. 检查订单状态是否为待支付（只有待支付状态可以取消）
        if (!Order.STATUS_PENDING.equals(order.getStatus())) {
            throw new IllegalArgumentException("订单状态不正确，无法取消");
        }
        
        // 3. 更新订单状态为已取消
        Date now = new Date();
        order.setStatus(Order.STATUS_CANCELLED);
        order.setUpdateTime(now);
        
        // 4. 更新商品状态为在售
        SecondHandItem item = secondHandItemRepository.findById(order.getItemId())
            .orElseThrow(() -> new IllegalArgumentException("商品不存在"));
        item.setStatus("on_sale");
        secondHandItemRepository.save(item);
        
        // 5. 保存更新后的订单
        return orderRepository.save(order);
    }

    @Override
    public Optional<Order> findByOrderNo(String orderNo) {
        return orderRepository.findByOrderNo(orderNo);
    }
    
    @Override
    public Order getOrderByOrderNo(String orderNo) {
        return orderRepository.findByOrderNo(orderNo)
            .orElseThrow(() -> new IllegalArgumentException("订单不存在"));
    }

    @Override
    public List<Order> listByUserAndType(Long userId, String type) {
        if (userId == null) {
            throw new IllegalArgumentException("用户ID不能为空");
        }
        String normalizedType = type == null ? "buy" : type.trim().toLowerCase();
        return switch (normalizedType) {
            case "buy" -> orderRepository.findByBuyerIdOrderByCreateTimeDesc(userId);
            case "sell" -> orderRepository.findBySellerIdOrderByCreateTimeDesc(userId);
            default -> throw new IllegalArgumentException("type 仅支持 buy 或 sell");
        };
    }

    /**
     * 生成唯一订单号
     * 格式：ORD + 年月日 + 6位随机数
     */
    private String generateOrderNo() {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        String dateStr = sdf.format(new Date());
        Random random = new Random();
        int randomNum = 100000 + random.nextInt(900000); // 生成6位随机数
        return "ORD" + dateStr + randomNum;
    }
}
